package com.inspur.dgov.bsp.system.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.inspur.dgov.bsp.system.entity.PubConfig;
import com.inspur.dgov.bsp.system.entity.PubDict;
import com.inspur.dgov.bsp.system.service.PubConfigService;
import com.inspur.dgov.bsp.system.service.PubDictService;
import com.inspur.dgov.bsp.system.service.TreeService;
import com.inspur.dgov.common.secure.dto.SecureUser;
import com.inspur.dgov.common.secure.utils.SecureUtil;
import com.inspur.dgov.common.tool.api.R;
import com.inspur.dgov.common.tool.constant.AppConstant;
import com.inspur.dgov.common.tool.node.TreeNode;
import com.inspur.dgov.common.tool.node.TreeNodeUtil;
import com.inspur.dgov.common.tool.utils.UniqueIdGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 字典类别信息 前端控制器
 * </p>
 *
 * @author chiyupei
 * @since 2020-04-17
 */
@RestController
@RequestMapping("/config")
@Api(value = "字典类别管理", tags = "字典类别接口")
public class PubConfigController {

    @Value("${tenant.default.id}")
    private String defaultTenantId;

    @Autowired
    private TreeService treeService;

    @Autowired
    private PubConfigService pubConfigService;

    @Autowired
    private PubDictService pubDictService;

    /**
     * 字典类别树
     */
    @GetMapping("/configTree")
    @ApiOperation(value = "字典类别树", notes = "字典类别树", position = 1)
    public R<List<TreeNode>> configTree() {
        List<TreeNode> tree = new ArrayList<>();
        Map<String, Object> config = new HashMap<>();
        SecureUser curUser = SecureUtil.getUser();
        String tenantId = curUser.getTenantId();
        if (!StrUtil.equals(this.defaultTenantId, tenantId)) {
            config.put("tenantId", tenantId);
        }
//        TreeNode node0 = new TreeNode();
//        node0.setId("0");
//        node0.setTitle("国家标准字典");
//        node0.setDisabled(true);
//        tree.add(node0);
//        TreeNode node1 = new TreeNode();
//        node1.setId("1");
//        node1.setTitle("地方标准字典");
//        node1.setDisabled(true);
//        tree.add(node1);
//        TreeNode node2 = new TreeNode();
//        node2.setId("2");
//        node2.setTitle("行业标准字典");
//        node2.setDisabled(true);
//        tree.add(node2);
//        TreeNode node3 = new TreeNode();
//        node3.setId("3");
//        node3.setTitle("自定义字典");
//        node3.setDisabled(true);
//        tree.add(node3);
        tree.addAll(this.treeService.configTree(config));
        return R.data(TreeNodeUtil.merge(tree));
    }

    /**
     * 字典类别唯一性校验
     *
     * @param value
     * @param id
     * @return
     */
    @PostMapping("/verifyUnique")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "value", value = "字典类别编码", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "字典类别ID", paramType = "query", dataType = "String")
    })
    @ApiOperation(value = "字典类别唯一性校验", notes = "传入字典类别编码和字典类别ID", position = 2)
    public R verifyUnique(@RequestParam(value = "value", required = true) String value,
                          @RequestParam(value = "id", required = false) String id) {
        if (StrUtil.hasEmpty(value)) {
            return R.fail("接口调用不合法");
        }

        QueryWrapper<PubConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PubConfig::getCode, value);
        if (StrUtil.isNotEmpty(id)) {
            queryWrapper.lambda().ne(PubConfig::getId, id);
        }

        //查出满足条件的所有记录
        List<PubConfig> list = this.pubConfigService.list(queryWrapper);
        if (ObjectUtil.isEmpty(list)) {
            return R.success("");
        }
        return R.fail("该字典类别编码已被使用");
    }

    /**
     * 新增字典类别
     *
     * @param config
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "新增字典类别", notes = "传入字典类别信息", position = 3)
    public R add(@RequestBody PubConfig config) {
        SecureUser curUser = SecureUtil.getUser();
        LocalDateTime now = LocalDateTime.now();
        Long id = UniqueIdGenerator.generateId();
        config.setId(id);
        config.setCreator(Long.valueOf(curUser.getUserId()));
        config.setCreateTime(now);
        config.setStatus(AppConstant.DB_STATUS_NORMAL);
        config.setTenantId(Long.valueOf(curUser.getTenantId()));
        boolean ret = this.pubConfigService.save(config);
        return R.status(ret);
    }

    /**
     * 通过ID查询字典类别
     *
     * @param id ID
     * @return 字典类别信息
     */
    @GetMapping("/edit/{id}")
    @ApiOperation(value = "通过ID查询字典类别", notes = "传入字典类别ID", position = 4)
    public R getById(@PathVariable String id) {
        return R.data(this.pubConfigService.getById(id));
    }

    /**
     * 更新字典类别
     *
     * @param config
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新字典类别", notes = "传入字典类别信息", position = 5)
    public R update(@RequestBody PubConfig config) {
        boolean ret = this.pubConfigService.updateConfig(config);
        return R.status(ret);
    }

    /**
     * 删除字典类别
     */
    @PostMapping("/remove")
    @ApiOperation(value = "删除字典类别", notes = "传入字典类别ID", position = 6)
    public R remove(@RequestParam(value = "configId", required = true) String configId) {
        //检查是否有关联字典项
        QueryWrapper<PubDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PubDict::getConfigId, configId);
        int count = this.pubDictService.count(queryWrapper);
        if (count > 0) {
            return R.fail("已有关联字典项，不能删除");
        }
        return R.status(this.pubConfigService.removeById(configId));
    }
}
